package jzoffer;

import leetcode.tree.TreeNode;

import java.util.LinkedList;

/**
 * @author MaoLin Wang
 * @date 2020/10/8 10:57 上午
 */
public class _27二叉树的镜像 {
    public  static TreeNode mirrorTree(TreeNode root) {
        if (root==null){
            return null;
        }
        TreeNode mirror=new TreeNode(root.val);
        preOrder(root.left,mirror,true);
        preOrder(root.right,mirror,false);
        return mirror;
    }
    public  static TreeNode mirrorTree2(TreeNode root) {
        if (root==null){
            return null;
        }
        LinkedList<TreeNode> stack=new LinkedList<>();
        stack.add(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.poll();
            TreeNode left = node.left;
            node.left=node.right;
            node.right=left;
            if (node.left!=null){
                stack.add(node.left);
            }
            if (node.right!=null){
                stack.add(node.right);
            }
        }
        return root;
    }

    private static void preOrder(TreeNode root, TreeNode mirror, boolean left) {
        if (root==null){
            return;
        }
        if (left){
            mirror.right=new TreeNode(root.val);
            mirror=mirror.right;
        }else {
            mirror.left=new TreeNode(root.val);
            mirror=mirror.left;
        }
        preOrder(root.left,mirror,true);
        preOrder(root.right,mirror,false);
    }

    public static void main(String[] args) {
        TreeNode root=new TreeNode(10);
        root.left=new TreeNode(12);
        root.right=new TreeNode(6);
        root.left.left=new TreeNode(8);
        root.left.right=new TreeNode(3);
        root.left.left.left=new TreeNode(11);

        TreeNode treeNode = mirrorTree2(root);
        System.out.println(treeNode);
        /*
               10           10
             12   6       6   12
           8   3                8
          11                      11
         */

    }

}
